'use strict';

const Controller = require('egg').Controller;
class SpecificationAttrController extends Controller {
  /**
     * @api {Post} /api/specificationAttr 添加规格属性的名称和值
     * @apiGroup 商品规格
     * @apiParam {INTEGER} specification_id   规格id（必填)
     * @apiParam {String}  name               规格属性名称（必填)
     * @apiParamExample 参数模板
     {
       "specification_id": 1,
       "name": "红色",
      }
     * @apiSuccessExample 成功返回
     {
          "msg": "添加成功",
          "result": {
              "specification_id": "1",
              "specification_attr_id": 6,
              "specification_attr_name": "红色"
          }
      }
     *
     * @apiErrorExample 错误返回
     * {
     *  "msg":"添加失败"
     * }
     *
     */

  async create() {
    const { ctx } = this;
    const { SpecificationAttr } = this.app.model.Tables.Shop;
    const dataObj = ctx.request.body;

    if (
      new ctx.helper.checkData(this, 'specification_id', 'name').checkDataRes
    ) {
      try {
        dataObj.user_id = this.ctx.adminInfo.id;
        dataObj.project_id = this.ctx.adminInfo.project_id;
        const result = await SpecificationAttr.create(dataObj);
        ctx.body = result
          ? ctx.response.success(
              {
                specification_id: result.specification_id,
                specification_attr_id: result.id,
                specification_attr_name: result.name,
              },
              '添加成功'
            )
          : ctx.response.error(result, '添加失败');
      } catch (error) {
        ctx.body = ctx.response.error(error.message);
      }
    }
  }
}

module.exports = SpecificationAttrController;
